package com.zenithmind.coding.controller;

import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.coding.controller.base.BaseController;
import com.zenithmind.coding.pojo.dto.ContestCreateDTO;
import com.zenithmind.coding.pojo.vo.ContestVO;
import com.zenithmind.coding.service.ContestService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 编程竞赛控制器 - 遵循单一职责原则，专门处理竞赛的基本CRUD操作
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Tag(name = "编程竞赛", description = "编程竞赛管理相关接口")
@RestController
@RequestMapping("/api/zenithMind/v1/contests")
@RequiredArgsConstructor
public class ContestController extends BaseController {

    private final ContestService contestService;

    @Operation(summary = "创建竞赛", description = "创建新的编程竞赛")
    @PostMapping
    public Result<ContestVO> createContest(@Valid @RequestBody ContestCreateDTO createDTO) {
        try {
            validateUserRole("ADMIN");
            ContestVO contest = contestService.createContest(createDTO);
            logOperation("创建竞赛", "竞赛标题: " + createDTO.getTitle());
            return success(contest);
        } catch (IllegalAccessException e) {
            logError("创建竞赛", "权限不足", e);
            return Result.fail("权限不足");
        }
    }

    @Operation(summary = "分页查询竞赛列表", description = "分页查询编程竞赛列表")
    @GetMapping
    public Result<PageResult<ContestVO>> getContestPage(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "竞赛状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "竞赛类型") @RequestParam(required = false) Integer type,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword) {
        validatePageParams(current, size);
        PageResult<ContestVO> result = contestService.getContestPage(current, size, status, type, keyword);
        return success(result);
    }

    @Operation(summary = "查询竞赛详情", description = "根据ID查询编程竞赛详情")
    @GetMapping("/{id}")
    public Result<ContestVO> getContestById(@Parameter(description = "竞赛ID") @PathVariable String id) {
        validateId(id, "竞赛ID");
        ContestVO contest = contestService.getContestById(id);
        logOperation("查询竞赛详情", "竞赛ID: " + id);
        return success(contest);
    }

    @Operation(summary = "更新竞赛", description = "更新编程竞赛信息")
    @PutMapping("/{id}")
    public Result<ContestVO> updateContest(
            @Parameter(description = "竞赛ID") @PathVariable String id,
            @Valid @RequestBody ContestCreateDTO updateDTO) {
        try {
            validateId(id, "竞赛ID");
            validateUserRole("ADMIN");
            ContestVO contest = contestService.updateContest(id, updateDTO);
            logOperation("更新竞赛", "竞赛ID: " + id);
            return success(contest);
        } catch (IllegalAccessException e) {
            logError("更新竞赛", "权限不足", e);
            return Result.fail("权限不足");
        }
    }

    @Operation(summary = "删除竞赛", description = "删除编程竞赛")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteContest(@Parameter(description = "竞赛ID") @PathVariable String id) {
        try {
            validateId(id, "竞赛ID");
            validateUserRole("ADMIN");
            Boolean result = contestService.deleteContest(id);
            logOperation("删除竞赛", "竞赛ID: " + id);
            return success(result);
        } catch (IllegalAccessException e) {
            logError("删除竞赛", "权限不足", e);
            return Result.fail("权限不足");
        }
    }

    @Operation(summary = "参加竞赛", description = "用户参加编程竞赛")
    @PostMapping("/{id}/join")
    public Result<Boolean> joinContest(@Parameter(description = "竞赛ID") @PathVariable String id) {
        validateId(id, "竞赛ID");
        String userId = getCurrentUserId();
        Boolean result = contestService.joinContest(id, userId);
        logOperation("参加竞赛", "竞赛ID: " + id);
        return success(result);
    }

    @Operation(summary = "退出竞赛", description = "用户退出编程竞赛")
    @PostMapping("/{id}/leave")
    public Result<Boolean> leaveContest(@Parameter(description = "竞赛ID") @PathVariable String id) {
        validateId(id, "竞赛ID");
        String userId = getCurrentUserId();
        Boolean result = contestService.leaveContest(id, userId);
        logOperation("退出竞赛", "竞赛ID: " + id);
        return success(result);
    }

    @Operation(summary = "获取竞赛参与者", description = "获取竞赛参与者列表")
    @GetMapping("/{id}/participants")
    public Result<List<Object>> getContestParticipants(
            @Parameter(description = "竞赛ID") @PathVariable String id,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "100") Integer limit) {
        validateId(id, "竞赛ID");
        List<Object> participants = contestService.getContestParticipants(id, limit);
        return success(participants);
    }

    @Operation(summary = "获取竞赛排行榜", description = "获取竞赛排行榜")
    @GetMapping("/{id}/leaderboard")
    public Result<List<Object>> getContestLeaderboard(
            @Parameter(description = "竞赛ID") @PathVariable String id,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        validateId(id, "竞赛ID");
        List<Object> leaderboard = contestService.getContestLeaderboard(id, limit);
        return success(leaderboard);
    }

    @Operation(summary = "开始竞赛", description = "开始编程竞赛")
    @PostMapping("/{id}/start")
    public Result<Boolean> startContest(@Parameter(description = "竞赛ID") @PathVariable String id) {
        try {
            validateId(id, "竞赛ID");
            validateUserRole("ADMIN");
            Boolean result = contestService.startContest(id);
            logOperation("开始竞赛", "竞赛ID: " + id);
            return success(result);
        } catch (IllegalAccessException e) {
            logError("开始竞赛", "权限不足", e);
            return Result.fail("权限不足");
        }
    }

    @Operation(summary = "结束竞赛", description = "结束编程竞赛")
    @PostMapping("/{id}/end")
    public Result<Boolean> endContest(@Parameter(description = "竞赛ID") @PathVariable String id) {
        try {
            validateId(id, "竞赛ID");
            validateUserRole("ADMIN");
            Boolean result = contestService.endContest(id);
            logOperation("结束竞赛", "竞赛ID: " + id);
            return success(result);
        } catch (IllegalAccessException e) {
            logError("结束竞赛", "权限不足", e);
            return Result.fail("权限不足");
        }
    }

    @Operation(summary = "获取用户参与的竞赛", description = "获取用户参与的竞赛列表")
    @GetMapping("/my-contests")
    public Result<List<ContestVO>> getUserContests(
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = getCurrentUserId();
        List<ContestVO> contests = contestService.getUserContests(userId, limit);
        return success(contests);
    }
}
